package top.birdhk.TestAPI.transorm;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import top.birdhk.TestAPI.beans.SensorReading;


/**
 *
 */
public class Transfrom_RichFunction {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> inputSream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

//        env.setParallelism(1);

        SingleOutputStreamOperator<SensorReading> dataStream = inputSream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });



        DataStream<Tuple2<String, Integer>> resultStream = dataStream.map(new MapFunction<SensorReading, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(SensorReading sensorReading) throws Exception {
                return new Tuple2<>(sensorReading.getId(),sensorReading.getId().length());
            }
        });


        SingleOutputStreamOperator<Tuple2<String, Integer>> richMapStream = dataStream.map(new MyMapper());

        richMapStream.print("Rich");


        env.execute();


    }


    public static class MyMapper extends RichMapFunction<SensorReading,Tuple2<String,Integer>>{

        @Override
        public Tuple2<String, Integer> map(SensorReading sensorReading) throws Exception {
            return new Tuple2<>(sensorReading.getId(),getRuntimeContext().getIndexOfThisSubtask());
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            // 初始化工作，一般是定义状态，或者建立数据库连接
            System.out.println("open");
        }

        @Override
        public void close() throws Exception {
            // 关闭连接和清空状态的收尾工作
            System.out.println("close");
        }
    }


}
